# -*- coding: utf-8 -*-
from urllib import quote
from search.basesearch import basesearch
"""

Ricerche in Google via API 0

Parametri: Standard URL Arguments vedere anche Standard URL Arguments in http://code.google.com/intl/it/apis/ajaxsearch/documentation/reference.html
* start: 
* rsz: small 4, large=8 
* oe: charset di output;
* ie: charset di input;
#* hl: nazione di ricerca (it, en, de, es, fr...);
* v: versione, attualmente è da considerarsi costante a 1.0;
* q: la query, ricordandosi di passare il testo per un url encoder.

Un classico URL di richiesta somiglierà a:
http://code.google.com/intl/it/apis/ajaxsearch/documentation/reference.html

Standard URL Base Address'
Each search endpoint is accessed through a standard URL. The following table lists the URL used to access each service.

Searcher  Base Url
Web Search    http://ajax.googleapis.com/ajax/services/search/web
Local Search  http://ajax.googleapis.com/ajax/services/search/local
Video Search  http://ajax.googleapis.com/ajax/services/search/video
Blog Search   http://ajax.googleapis.com/ajax/services/search/blogs
News Search   http://ajax.googleapis.com/ajax/services/search/news
Book Search   http://ajax.googleapis.com/ajax/services/search/books
Image Search  http://ajax.googleapis.com/ajax/services/search/images
Patent Search   http://ajax.googleapis.com/ajax/services/search/patentN

http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&oe=utf-8&ie=utf-8&hl=it&v=1.0&q=keywords+da+cercare 
"""

class GoogleJson(basesearch):
  def __init__(self,logger,host,port="80",path="/",timeout=1.5):
    basesearch.__init__(self,logger,host,port,path,timeout)
    self.logger.debug("%s Init Host:%s port:%s path:%s"%(__name__,self.host,self.port,self.path))
    self._searcher="web"
    self._searchkey="searcher"
    self._searchers=["web","local","video","blogs","news","books","images","patentN"]
  def _makeUrl(self):
     self.url=None
     qs=quote(self.env_requests['qs'])
     if self.parameters.has_key(self._searchkey) and self.parameters[self._searchkey] in self._searchers:
       self._searcher=self.parameters[self._searchkey]
     self.url="http://%s/%s/%s?q=%s&%s"%(self.host,self.path,self._searcher,qs,self._makeSourceRequest())
     self.logger.debug("MakeUrl [%s]"%self.url)
  def setResult(self,res):
     self.logger.debug("result [%s] bytes"%len(res))
     try:
      self.result=unicode(res,"utf-8")
     except:
       #Todo gestire l'eccezzione
       self.result="Unicode error"
     